<?php
/*
 * @version 0.4
 */
function __autoload($class)
{
	__init_autoload();
	$file = __find_class($class);
	if ($file == false) {
		$file = $GLOBALS['libdb']->$class;
//		if (!file_exists($file)) 
//		{
//			$file = $GLOBALS['libdir'].$class.'.php';
//		}
	}
	if(!file_exists($file)) {
		throw new Exception("Class $class not found!");
	}
	include($file);
	if (!class_exists($class) && !interface_exists($class)) throw new Exception("Class $class not found!");
	if (method_exists($class, 'init')) 
		eval($class.'::init();');
}


function __init_autoload(){
	if (!class_exists('Config', false)) 
	{
		require_once $GLOBALS['libdir'].'Config.php';
	}
	if (!@$GLOBALS['libdb'])
	{
		@$GLOBALS['libdb'] = new Config('libdb');
		@$GLOBALS['libdirs'] = $GLOBALS['libdb']->library_directories;
	}
}

function __find_class($class) {
	$libs = @$GLOBALS['libdirs'];
	for($x=0;$x<count($libs);$x++) {
		$file = $libs[$x].$class.'.php';
		//echo $file;
		if (file_exists($file)) {
			//echo ' ++++++!<br/>';
			return $file;
		}
		//echo '<br/>';
	}
	return false;
}

function lib(string $library) {
	if (array_search($library, $GLOBALS['libdirs'])) return true;
	$libdir = $GLOBALS['libdir'].str_replace('.', '/', $library);
        Log::target('system.log');
        Log::put("Linking $library...");
        if (file_exists($libdir.'.php')) {
            Log::put("Linked class: $library");
            require_once $libdir.'.php';
//            ($libdir.'.php');
        } else {
            if (strpos($libdir, '*') > -1) {
                $libdir = str_replace('*', '', $libdir);
                __link_dir($libdir);
            } else {
                Log::put("Linked directory: $library");
                $GLOBALS['libdirs'][] = $libdir;
            }
        }
}


function __link_dir($dir) {
    if (($incdir = opendir($dir)) != false)
    {
            while (false !== ($file = readdir($incdir))){
                if (strpos($file, '.') == 0) continue;
                if (is_file($dir.$file)) {
                    log::put('Using: '.$dir.$file);
                    require_once($dir.$file);
                } else {
                    if (!in_array($file, array('.', '..'))) {
                        __link_dir($dir.$file.'/');
                    }
                }

            }
    }
}

?>